package com.ssish.common.insurance.utils;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;

import org.apache.commons.lang3.StringUtils;

/**
 * 
 * <P>
 * Description: 推特开源的id生成器snowflake,用于生成唯一id替代uuid,效率比uuid高
 * </P>
 * 
 * @ClassName: IdWorkerUtil
 * @author jie.xu 2017年3月22日 下午1:22:17
 * @see TODO
 */
public class IdWorkerUtil {
	private static final IdWorker idWorker;
	static {
		// 2个参数都不能大于31,所以取模
		idWorker = new IdWorker(IdWorker.getLocalIp4() % 32,
				IdWorker.getIp4LastChar() % 32);
	}

	private IdWorkerUtil() {

	}

	public static void main(String[] args) {
		System.out.println(IdWorker.getLocalIp4());
		System.out.println(IdWorker.getIp4LastChar());
		for (int i = 0; i < 100; i++) {
			System.out.println(IdWorkerUtil.nextId() + "====" + i);
		}
	}

	/**
	 * 
	 * <p>
	 * Title: 获取一个唯一id
	 * </p>
	 * <p>
	 * Description: TODO
	 * </p>
	 * 
	 * @return
	 * @author jie.xu 2017年3月28日 下午3:12:49
	 */
	public static Long nextId() {
		return idWorker.nextId();
	}
}

final class IdWorker {
	private final long twepoch = 1288834974657L;
	private final long workerIdBits = 5L;
	private final long datacenterIdBits = 5L;
	private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
	private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
	private final long sequenceBits = 12L;
	private final long workerIdShift = sequenceBits;
	private final long datacenterIdShift = sequenceBits + workerIdBits;
	private final long timestampLeftShift = sequenceBits + workerIdBits
			+ datacenterIdBits;
	private final long sequenceMask = -1L ^ (-1L << sequenceBits);

	private long workerId;
	private long datacenterId;
	private long sequence = 0L;
	private long lastTimestamp = -1L;

	/**
	 * 
	 * <p>
	 * Title: Constructor
	 * </p>
	 * <p>
	 * Description: 实例化
	 * </p>
	 * 
	 * @param workerId
	 * @param datacenterId
	 */
	public IdWorker(long workerId, long datacenterId) {
		if (workerId > maxWorkerId || workerId < 0) {
			throw new IllegalArgumentException(String.format(
					"worker Id can't be greater than %d or less than 0",
					maxWorkerId));
		}
		if (datacenterId > maxDatacenterId || datacenterId < 0) {
			throw new IllegalArgumentException(String.format(
					"datacenter Id can't be greater than %d or less than 0",
					maxDatacenterId));
		}
		this.workerId = workerId;
		this.datacenterId = datacenterId;
	}

	/**
	 * 
	 * <p>
	 * Title: nextId
	 * </p>
	 * <p>
	 * Description: 获取一个id
	 * </p>
	 * 
	 * @return
	 * @author jie.xu 2017年3月22日 下午1:25:26
	 */
	public synchronized long nextId() {
		long timestamp = timeGen();
		if (timestamp < lastTimestamp) {
			throw new RuntimeException(
					String.format(
							"Clock moved backwards.  Refusing to generate id for %d milliseconds",
							lastTimestamp - timestamp));
		}
		if (lastTimestamp == timestamp) {
			sequence = (sequence + 1) & sequenceMask;
			if (sequence == 0) {
				timestamp = tilNextMillis(lastTimestamp);
			}
		} else {
			sequence = 0L;
		}

		lastTimestamp = timestamp;

		return ((timestamp - twepoch) << timestampLeftShift)
				| (datacenterId << datacenterIdShift)
				| (workerId << workerIdShift) | sequence;
	}

	protected long tilNextMillis(long lastTimestamp) {
		long timestamp = timeGen();
		while (timestamp <= lastTimestamp) {
			timestamp = timeGen();
		}
		return timestamp;
	}

	protected long timeGen() {
		return System.currentTimeMillis();
	}

	private static String[] getLocalIp4Array() {
		String[] strs = null;
		try {
			InetAddress local = Inet4Address.getLocalHost();
			String ip4 = local.getHostAddress();
			strs = StringUtils.split(ip4, ".");
			return strs;
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		return null;

	}

	public static Long getLocalIp4() {
		String[] strs = getLocalIp4Array();
		StringBuilder sb = new StringBuilder();
		for (String string : strs) {
			sb.append(string);
		}
		return Long.valueOf(sb.toString());
	}

	public static Long getIp4LastChar() {
		String[] strs = getLocalIp4Array();
		return Long.valueOf(strs[strs.length - 1]);
	}
}